package com.jbit.controller;

import com.jbit.aliyun.utils.Sample;
import com.jbit.dto.DmUser;
import com.jbit.redis.utils.RedisUtils;
import com.jbit.service.DmUserService;
import com.jbit.utils.Md5Utils;
import com.jbit.utils.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user/api/p")
public class RegisterController {
    @Resource
    RedisUtils redisUtils;

    @Resource
    DmUserService dmUserService;
    @PostMapping("/code")
    public ResponseEntity code(@RequestBody DmUser user){
        if(redisUtils.hasKey(user.getPhone())){
            return ResponseEntity.sendError("1002");
        }
        //生成随机数
        String random = (int)((Math.random() * (1000000 - 100000) + 100000)) + "";
        try {
            Sample.sendSms(user.getPhone(),random);
            redisUtils.set(user.getPhone(),random,300L);
            return ResponseEntity.sendSuccess(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.sendError("1007");
    }
    @PostMapping("/register")
    public ResponseEntity register(@RequestBody DmUser dmUser){
        if (dmUserService.queryUserByPhone(dmUser.getPhone()) != null){
            return ResponseEntity.sendError("1003");
        }else{
            String code = redisUtils.get(dmUser.getPhone()).toString();
            if (dmUser.getVcode().equals(code)){
                String md5Pwd = Md5Utils.generalKey(dmUser.getPassword());
                dmUser.setPassword(md5Pwd);
                dmUserService.addUser(dmUser);
                redisUtils.deleteKey(dmUser.getPhone());
                return ResponseEntity.sendSuccess(null);
            }else{
                return ResponseEntity.sendError("1004");
            }
        }
    }
}
